package com.party.mobile.task;

import com.party.common.utils.DateUtils;
import com.party.core.model.analysis.StatisticsFunnel;
import com.party.core.service.analysis.IStatisticsFunnelService;
import com.party.core.service.member.IMemberGroupService;
import com.party.mobile.biz.analysis.StatisticsFlowBizService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;

import static java.util.concurrent.Executors.newFixedThreadPool;

/**
 * 漏斗转化的定时任务
 *
 * @author yifeng
 * @date 2018/9/11 0011
 * @time 下午 17:50
 */
@Component(value = "quartzForFunnel")
public class QuartzForFunnel {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private IStatisticsFunnelService statisticsFunnelService;
    @Autowired
    private StatisticsFlowBizService statisticsFlowBizService;

    @Scheduled(cron = "0 0 4 * * ?")
    public void analysisFunnel() {
        logger.info("处理漏斗开始 《《《《《《《《《《《《《");
        ExecutorService threadPool = newFixedThreadPool(5);
        Date yesterday = DateUtils.yesterday();
        List<String> partnerIds = memberGroupService.getAllPartnerIds();
        List<StatisticsFunnel> statisticsFunnels = statisticsFunnelService.list(new StatisticsFunnel());
        for (StatisticsFunnel statisticsFunnel : statisticsFunnels) {
            try {
                for (String partnerId : partnerIds) {
                    try {
                        threadPool.execute(new Runnable() {
                            @Override
                            public void run() {
                                statisticsFlowBizService.analysisFunnel(statisticsFunnel.getId(), partnerId, yesterday);
                            }
                        });
                    } catch (Exception e) {
                        logger.error("{} 机构处理{} 漏斗异常", partnerId, statisticsFunnel.getId(), e);
                        continue;
                    }
                }
            } catch (Exception e) {
                logger.error("{} 漏斗异常", statisticsFunnel.getId(), e);
                continue;
            }
        }
        logger.info("处理漏斗结束 《《《《《《《《《《《《《");
    }
}
